#include "link/include/factory.h"
int get_command(MYSQL* conn,pnode_t pnod)
{
    int newfd=pnod->newfd;
    int opt=0;
    int len=0;
    char arg[128]={0};
    if(!recv(newfd,&opt,4,0)){return -1;}
    if(!recv(newfd,&len,4,0)){return -1;}
    if(len!=0)
    {//接收客户端发来的命令结构体
        recv(newfd,arg,len,0);
    }
    wrlog(conn,opt,arg,pnod);
    switch(opt){
    case 1:
        return do_cd(conn,newfd,arg,pnod);
    case 2:
        return do_ls(conn,newfd,pnod);
    case 3:
        return do_gets(conn,newfd,arg,pnod);
    case 4:
        return do_puts(conn,newfd,arg,pnod);
    case 5:
        return do_remove(conn,newfd,arg,pnod);
    case 6:
        return do_pwd(conn,newfd,pnod);
    case 7:
        return do_mkdir(conn,newfd,arg,pnod);
    default:
        return -1;
    }
    return 0;
}
int do_cd(MYSQL* conn,int newfd,char* arg,pnode_t pnod)
{
    MYSQL_RES *res;
    MYSQL_ROW row;
    unsigned int num;
    char query[256]={0};
    char path[256]={0};
    strcat(path,"/");
    printf("pnod->levrl=%d\n",pnod->level);
    train_t dt;
    int ret;
    if(0==strcmp(arg,".."))
    {
        if(0==pnod->level)
        {//当前正处于根目录
            dt.datalen=0;
            send(newfd,&dt,4,0);
            return 0;//立即返回
        }
        --pnod->level;
    }else
    {
        sprintf(query,"select code from repository where precode=%d and filename='%s'",pnod->pathcode[pnod->level],arg);
        sql_query(conn,&res,query,&num);
        if(res)
        {
            if((row=mysql_fetch_row(res))!=NULL)
            {//目标目录存在
                ++pnod->level;
                pnod->pathcode[pnod->level]=atoi(row[0]);
                mysql_free_result(res);
            }
            else{//目标目录不存在
                dt.datalen=0;
                send(newfd,&dt,4,0);
                mysql_free_result(res);
                return 0;//立即返回
            }
        }
    }
    for(int i=0;i<=pnod->level;++i)
    {//拼接用户当前所处路径
        sprintf(query,"select filename from repository where code=%d",pnod->pathcode[i]);
        puts(query);
        sql_query(conn,&res,query,&num);
        printf("fetch now\n");
        row=mysql_fetch_row(res);
        printf("row=%s\n",row[0]);
        strcat(path,row[0]);
        strcat(path,"/");
        mysql_free_result(res);
        bzero(query,sizeof(query));
    }
    strcpy(dt.buf,path);
    dt.datalen=strlen(dt.buf);
    ret=send(newfd,&dt,4+dt.datalen,0);
    if(-1==ret){return -1;}
    return 0;
}
int do_ls(MYSQL* conn,int newfd,pnode_t pnod)
{
    int ret;
    char pbuf[256]={0};
    strcpy(pbuf,pnod->homepath);
    train_t dt;
    bzero(&dt,sizeof(train_t));
    MYSQL_RES *res;
    MYSQL_ROW row;
    char query[256]={0};
    unsigned int num;
    char filename[64]={0};
    int size;
    sprintf(query,"select filename,size from repository where precode=%d",pnod->pathcode[pnod->level]);
    printf("%s\n",query);
    sql_query(conn,&res,query,&num);
    if(res)
    {
        while((row=mysql_fetch_row(res))!=NULL)
        {
            for(num=0;num<mysql_num_fields(res);++num)
            {
                if(0==num)
                {
                    strcpy(filename,row[num]);
                }else{
                    size=atoi(row[num]);
                }
            }
            if(-1==size)//判断是否为一个文件夹
            {
                sprintf(pbuf,"%-12sdirectory   %12dbytes",filename,0);
            }else{
                sprintf(pbuf,"%-12sregular file%12dbytes",filename,size);
            }
            strcat(dt.buf,pbuf);
            strcat(dt.buf,"\n");
        }
    }
    printf("buf%s\n",dt.buf);
    dt.datalen=strlen(dt.buf);
    ret=send(newfd,&dt,4+dt.datalen,0);
    if(-1==ret)
    {
        return -1;
    }
    return 0;
}
int do_gets(MYSQL* conn,int newfd,char* arg,pnode_t pnod)
{//接受用户上传的文件
    MYSQL_RES *res;
    MYSQL_ROW row;
    unsigned int num;
    char query[256]={0};
    int ret;
    int len;
    //接收文件大小
    int datalen;
    off_t fsize;    
    recv(newfd,&datalen,4,0);    
    recv(newfd,&fsize,datalen,0);    
    //接收即将发送的文件的md5码
    char md5[64]={0};
    recv(newfd,&len,4,0);
    recv(newfd,md5,len,0);
    sprintf(query,"select count(*) from repository where md5sum='%s'",md5);
    puts(query);
    sql_query(conn,&res,query,&num);
    if(res)
    {
        if((row=mysql_fetch_row(res))!=NULL)
        {
            int sig;
            if(!strcmp("0",row[0]))
            {//表示没有相同文件，同时向对端发送信号
		mysql_free_result(res); //row获取的十res当中的数据，要在row用完之后再释放
                sig=0;
                send(newfd,&sig,4,0);
                ret=recv_file(newfd,md5,pnod,fsize);
            }else{//表示已有md5值相同的文件存在
		mysql_free_result(res); //及时释放，便于处理其他用户的接入请求
                sig=1;
                send(newfd,&sig,4,0);
            }
	    if(-1==ret){return -1;}
            bzero(query,sizeof(query));
            sprintf(query,"insert into repository (precode,owner,filename,size,md5sum) values (%d,'%s','%s',%ld,'%s')",pnod->pathcode[pnod->level],pnod->username,arg,fsize,md5);
            sql_insert(conn,query);
        }
    }
    return 0;
}
int do_puts(MYSQL* conn,int newfd,char* arg,pnode_t pnod)
{
    MYSQL_RES *res;
    MYSQL_ROW row;
    unsigned int num;
    char query[256]={0};
    char md5[64]={0};
    int sig;
    char buf[256]={0};
    strcpy(buf,pnod->homepath);
    sprintf(query,"select md5sum from repository where filename='%s' and precode=%d and owner='%s'",arg,pnod->pathcode[pnod->level],pnod->username);
    puts(query);
    sql_query(conn,&res,query,&num);
    if(res)
    {
        if((row=mysql_fetch_row(res))!=NULL)
        {
            if(!strcmp(row[0],"0"))
            {//表示该文件为目录文件，暂不支持下载
                mysql_free_result(res);
                sig=-1;
                send(newfd,&sig,4,0);
            }else{
                sig=1;
                send(newfd,&sig,4,0);
                strcpy(buf,pnod->homepath);
                strcat(buf,"/");
                strcpy(md5,row[0]);
                strcat(buf,md5);
                printf("buf|%s|\n",buf);
                //res释放要及时，调用trans_file之后释放就会出问题，
                //不知道是不是MySQL数据库处理数据的方式引起的问题，待后期考证
                mysql_free_result(res);
                int fd=open(buf,O_RDONLY);
                trans_file(newfd,fd);
            }
        }else{//表示该文件不存在
                printf("没有该文件\n");
                mysql_free_result(res);
                sig=0;
                send(newfd,&sig,4,0);
            }

    }
    return 0;
}
int do_remove(MYSQL* conn,int newfd,char* arg,pnode_t pnod)
{
    MYSQL_RES *res;
    MYSQL_ROW row;
    unsigned int num;
    char query[256]={0};
    char md5[64]={0};
    char pbuf[512]={0};
    int sig;
    sprintf(query,"select md5sum from repository where filename='%s' and precode=%d and owner='%s'",arg,pnod->pathcode[pnod->level],pnod->username);
    puts(query);
    sql_query(conn,&res,query,&num);
    if(res)
    {//res不为空说明数据库中有对应记录，错误！！！说明sql查询出问题了
        row=mysql_fetch_row(res);
        if((row!=NULL))
        {//row为NULL说明数据库中没有对应记录
            if(!strcmp(row[0],"0"))
            {//暂时还没有实现删除目录的功能
                mysql_free_result(res);
                sig=-1;
                send(newfd,&sig,4,0);
            }else{
                strcpy(md5,row[0]);
                strcpy(pbuf,pnod->homepath);
                strcat(pbuf,"/");
                strcat(pbuf,md5);
                printf("pbuf|%s|\n",pbuf);
                sprintf(query,"select count(*) from repository where md5sum='%s'",md5);
                puts(query);
                printf("For deleting\n");
                mysql_free_result(res);
                sql_query(conn,&res,query,&num);//暂且先略去错误检查
                row=mysql_fetch_row(res);
                if(!strcmp(row[0],"1"))
                {//这边需要进行互斥操作
                    unlink(pbuf);
                    printf("shenchu\n");
                }
                mysql_free_result(res);
                sprintf(query,"delete from repository where precode=%d and filename='%s'",pnod->pathcode[pnod->level],arg);
                puts(query);
                sql_delete(conn,query);
                sig=0;
                send(newfd,&sig,4,0);
            }   
        }else{//表示没有该文件
            mysql_free_result(res);
            sig=1;
            send(newfd,&sig,4,0);
        }
    }    
    return 0;
}
int do_pwd(MYSQL* conn,int newfd,pnode_t pnod)
{//冗余的接口，等哪天有心情了再来处理它
    int ret;
    train_t dt;
    MYSQL_RES *res;
    MYSQL_ROW row;
    unsigned int num;
    char query[256]={0};
    char path[256]={0};
    strcat(path,"/");
    printf("pnod->levrl=%d\n",pnod->level);
    for(int i=0;i<=pnod->level;++i)
    {//拼接用户当前所处路径
        sprintf(query,"select filename from repository where code=%d",pnod->pathcode[i]);
        puts(query);
        sql_query(conn,&res,query,&num);
        printf("fetch now\n");
        row=mysql_fetch_row(res);
        printf("row=%s\n",row[0]);
        strcat(path,row[0]);
        strcat(path,"/");
        mysql_free_result(res);
        bzero(query,sizeof(query));
    }
    strcpy(dt.buf,path);
    dt.datalen=strlen(dt.buf);
    ret=send(newfd,&dt,4+dt.datalen,0);
    if(-1==ret)
    {
        return -1;
    }
    return 0;
}
int do_mkdir(MYSQL* conn,int newfd,char* arg,pnode_t pnod)
{
    MYSQL_RES *res;
    MYSQL_ROW row;
    unsigned int num;
    char query[256]={0};
    int  sig;//用于发送信号
    //先查询当前目录下是否有同名文件或文件夹
    sprintf(query,"select count(*) from repository where precode=%d and filename='%s'",pnod->pathcode[pnod->level],arg);
    puts(query);
    sql_query(conn,&res,query,&num);
    while((row=mysql_fetch_row(res))!=NULL)
    {
        printf("row[0]=%s|\n",row[0]);
        if(0==strcmp("0",row[0]))
        {//表示没有同名文件
            mysql_free_result(res);
            sprintf(query,"insert into repository (precode,owner,filename,size,md5sum) values (%d,'%s','%s',-1,0)",pnod->pathcode[pnod->level],pnod->username,arg);
            puts(query);
            sql_insert(conn,query);
            sig=0;
            send(newfd,&sig,4,0);
        }else{
            mysql_free_result(res);
            sig=-1;
            send(newfd,&sig,4,0);
        }
    }
    return 0;
}
